/**   
*    
* 项目名称：SmartKungFu   
* 类名称：MstRollController   
* 类描述：   
* 创建人：Wdd   
* 创建时间：2016年12月2日 上午10:09:03   
* 修改人：Wdd  
* 修改时间：2016年12月2日 上午10:09:03   
* 修改备注：   
* @version    
*    
*/
package com.lst.controller;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.github.miemiedev.mybatis.paginator.domain.Paginator;
import com.lst.common.BaseController;
import com.lst.common.CommonEnum;
import com.lst.exception.MyException;
import com.lst.model.FolPara;
import com.lst.model.MstButton;
import com.lst.model.MstRoll;
import com.lst.model.MstUser;
import com.lst.service.MstButtonService;
import com.lst.service.MstRollService;
import com.lst.utils.CommonUtils;
import com.lst.utils.DateUtil;

/**
 * @ClassName: MstRollController
 * @Description: 优惠券管理
 * @author Wdd
 * @date 2016年12月2日 上午10:09:03
 *
 */
@Controller
@RequestMapping("/mstRollController")
public class MstRollController extends BaseController {
	
	@Autowired
	private MstButtonService mstButtonService;
	
	@Autowired
	private MstRollService mstRollService;
	
	/**
	 * 
	* @Title: Main
	* @Description: 列表页跳转
	* @param @param menuId
	* @param @param page
	* @param @param rows
	* @param @param index_exp
	* @param @param index_che
	* @param @param minDate
	* @param @param maxDate
	* @param @param typeFol
	* @param @param ariTypeFol
	* @param @return
	* @param @throws MyException    设定文件
	* @return ModelAndView    返回类型
	* @throws
	 */
	@RequestMapping(value = "/Main")
	public ModelAndView Main(
			@RequestParam(required = false) int menuId,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGE)Integer page,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGESIZE) Integer rows,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che,
			@RequestParam(required = false,defaultValue = "") String minDate,
			@RequestParam(required = false,defaultValue = "") String maxDate,
			@RequestParam(required = false,defaultValue = "") String typeFol,
			@RequestParam(required = false,defaultValue = "") String ariTypeFol) throws MyException {
		Date startDate = new Date();
		logger.info("Main begin: " + startDate);

		ModelAndView mv = new ModelAndView(CommonEnum.FORWARD_VIEW_MAIN_KUNGFU + "/roll_list");

		// 查询用户权限按钮
		MstUser mstUser = this.getMySession().getMstUser();
		List<MstButton> btns = CommonUtils.readPermissionWithBtn(menuId, mstUser, mstButtonService);

		//写参数
		FolPara folPara = new FolPara();
		folPara.setPage(page);
		folPara.setRows(rows);
		folPara.setMinDate(minDate);
		folPara.setMaxDate(maxDate);
		folPara.setMenuId(menuId);
		folPara.setTypeFol(ariTypeFol);
		folPara.setAriTypeFol(ariTypeFol);

		mv.addObject("btns", btns);
		mv.addObject("folPara", folPara);

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("Main end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	/**
	 * 
	* @Title: queryList
	* @Description: 查询分页list
	* @param @param page
	* @param @param rows
	* @param @param sort
	* @param @param order
	* @param @param minDate
	* @param @param maxDate
	* @param @param type
	* @param @param ariType
	* @param @return    设定文件
	* @return Object    返回类型
	* @throws
	 */
	@RequestMapping(value = "/queryList")
	@ResponseBody
	public Object queryList(@RequestParam(required = false, defaultValue = CommonEnum.SYSTEMPAGE_PAGE) Integer page, 
			@RequestParam(required = false, defaultValue = CommonEnum.SYSTEMPAGE_PAGESIZE) Integer rows,
			@RequestParam(required = false,defaultValue = "")String sort,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEM_ORDER_DESC)String order,
			@RequestParam(required = false,defaultValue = "") String minDate,
			@RequestParam(required = false,defaultValue = "") String maxDate,
			@RequestParam(required = false,defaultValue = "") String type,
			@RequestParam(required = false,defaultValue = "") String ariType) {
		Date startDate = new Date();
		logger.info("queryList begin: " + startDate);

		/**
		 * 查询用户课程信息
		 */
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("isDeleted", 0);
		reqMap.put("enabled", 1);
		
		if(StringUtils.isEmpty(sort)){
			reqMap.put("orderByClause","r.createdate desc");
		} else{
			reqMap.put("orderByClause",sort + " " + order);
		}

		if(!StringUtils.isBlank(minDate) && !StringUtils.isBlank(maxDate)){
			try {
				if(DateUtil.parse(minDate).after(DateUtil.parse(maxDate))){
					reqMap.put("minDate", maxDate + DateUtil.START_DATE_HMS);
					reqMap.put("maxDate", minDate + DateUtil.END_DATE_HMS) ;
				}else{
					reqMap.put("minDate", minDate + DateUtil.START_DATE_HMS);
					reqMap.put("maxDate", maxDate + DateUtil.END_DATE_HMS);
				}
			} catch (ParseException e) {
				logger.error("queryList error: " ,e);
			}
		}	
		
		if(!StringUtils.isBlank(type)){
			reqMap.put("type", Integer.parseInt(type));
		}
		if(!StringUtils.isBlank(ariType)){
			reqMap.put("ariType", Integer.parseInt(ariType));
		}

		PageBounds pageBounds = new PageBounds(page, rows);
		List<MstRoll> list = mstRollService.queryByList(reqMap, pageBounds);

		PageList<MstRoll> pageList = (PageList<MstRoll>) list;
		Paginator paginator = pageList.getPaginator();

		HashMap<String, Object> indexPages = new HashMap<String, Object>();
		// indexPages.put("paginator", paginator);
		// indexPages.put("totalRows", paginator.getTotalCount());
		// indexPages.put("pageSize", paginator.getLimit());
		// indexPages.put("pageNumber", paginator.getPage());
		indexPages.put("total", paginator.getTotalCount());
		indexPages.put("rows", list);

		logger.info("queryList end run(s): " + DateUtil.calLastedTime(startDate));

		return indexPages;
	}
	
	/**
	 * 
	* @Title: edit
	* @Description: 跳转修改页
	* @param @param id
	* @param @param index_exp
	* @param @param index_che
	* @param @param type
	* @param @return    设定文件
	* @return ModelAndView    返回类型
	* @throws
	 */
	@RequestMapping(value = "/edit")
	public ModelAndView edit(
			@RequestParam(required = false, defaultValue = "") String id,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) Integer type) {
		Date startDate = new Date();
		logger.info("edit begin: " + startDate);
		
		ModelAndView mv = new ModelAndView(CommonEnum.FORWARD_VIEW_MAIN_KUNGFU + "roll_edit");

		if (!StringUtils.isBlank(id)) {
			// 获取用户信息
			MstRoll mstRoll = mstRollService.selectByPrimaryKey(Integer.parseInt(id));
			
			if(mstRoll.getAritype().equals(CommonEnum.SYSCODE_YH_TYPE_MJ)){
				String[] obj = mstRoll.getValue().split(";");
				mstRoll.setMan(obj[0]);
				mstRoll.setJian(obj[1]);
			}else if((mstRoll.getAritype().equals(CommonEnum.SYSCODE_YH_TYPE_DZ))){
				mstRoll.setDazhe(mstRoll.getValue());
			}else if((mstRoll.getAritype().equals(CommonEnum.SYSCODE_YH_TYPE_ZJ))){
				mstRoll.setZhijian(mstRoll.getValue());
			}
			
			mv.addObject("mstRoll", mstRoll);
		}

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);
		
		if(type.equals(CommonEnum.SYSCODE_YHQ_TYPE_KC)){
			//课程
			mv.addObject("menuName", "课程管理");
			mv.addObject("menuUrl", "gymnasiumDetailController/list");
		}else if(type.equals(CommonEnum.SYSCODE_YHQ_TYPE_HD)){
			//活动
			mv.addObject("menuName", "活动管理");
			mv.addObject("menuUrl", "projectInfoController/list");
		}

		logger.info("edit end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}
	
	/**
	 * 
	* @Title: delList
	* @Description: 删除优惠券信息
	* @param @param ids
	* @param @return
	* @param @throws MyException    设定文件
	* @return boolean    返回类型
	* @throws
	 */
	@RequestMapping("delList")
	@ResponseBody
	public boolean delList(
			@RequestParam(required = true) String  ids ) throws MyException{
		Date startDate = new Date();
		logger.info("delList begin: "  + startDate);

		boolean flag = false;

		MstUser mstUser = this.getMySession().getMstUser();

		Map<String, Object> reqMap = new HashMap<String,Object>();
		reqMap.put("updateUser", mstUser.getId());
		reqMap.put("ids", ids);

		try {
			mstRollService.delList(reqMap);
			flag  = true;
		} catch (Exception e) {
			logger.error("delList error: " ,e);
		}

		logger.info("delList end run(s): "  + 	
				DateUtil.calLastedTime(startDate));

		return flag;
	}
	
	/**
	 * 
	* @Title: save
	* @Description: 添加优惠券
	* @param @param mstRoll
	* @param @param br
	* @param @param folPara
	* @param @param request
	* @param @return
	* @param @throws MyException    设定文件
	* @return String    返回类型
	* @throws
	 */
	@RequestMapping(value = "/save",method = RequestMethod.POST)
	public String save(
			@Valid MstRoll mstRoll,
			BindingResult br,
			FolPara folPara, 
			HttpServletRequest request) throws MyException {
		Date startDate = new Date();
		logger.info("save begin: " + startDate);
		
		String index_exp = request.getParameter("index_exp");
		String index_che = request.getParameter("index_che");

		MstUser sysUser = this.getMySession().getMstUser();

		//执行业务层代码
		try {
			//拦截非法请求参数
			if (br.hasErrors()){
				List<ObjectError> ers = br.getAllErrors();
				logger.info("--------------form parameter error start-----------------------");

				for(ObjectError er : ers){
					logger.info("save faile with parameter illegal: " + er.getDefaultMessage() );
				}

				logger.info("--------------form parameter error end-----------------------");
			} else {
				
				mstRollService.saveInfo(mstRoll, sysUser);
			}
		} catch (Exception e) {
			logger.error("save error: " , e);
		}

		StringBuffer sb = new StringBuffer("?");
		sb.append("menuId=" + folPara.getMenuId());
		sb.append("&page=" + folPara.getPage());
		sb.append("&pageSize=" + folPara.getPageSize());
		sb.append("&index_exp=" + index_exp);
		sb.append("&index_che=" + index_che);
		
		sb.append("&index_exp=" + folPara.getIndex_exp());
		sb.append("&index_che=" + folPara.getIndex_che());

		logger.info("save end run(s): " + DateUtil.calLastedTime(startDate));
		
		String str = "";
		
		if(mstRoll.getType().equals(CommonEnum.SYSCODE_YHQ_TYPE_KC)){
			//课程
			str = "redirect:/gymnasiumDetailController/list" + sb.toString();
		}else if(mstRoll.getType().equals(CommonEnum.SYSCODE_YHQ_TYPE_HD)){
			//活动
			str = "redirect:/projectInfoController/list" + sb.toString();
		}
		
		return str;
	}
}
